<template>
  <AddButton buttonText="新增节点" @click="handleAdd" />
  <el-table :data="tableSource" style="width: 100%">
    <el-table-column prop="ip" label="IP" />
    <el-table-column prop="name" label="设备名" />
    <el-table-column prop="icon" label="图标">
      <template #default="{ row }">
        <img
          v-if="row.icon"
          :src="getIconUrl(row.icon)"
          style="width: 20px; height: 20px"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="{ row }">
        <EditButton @click="handleEdit(row)" />
        <DeleteButton @click="handleDelete(row)" />
      </template>
    </el-table-column>
  </el-table>
  <AddNodeDialog
    ref="addNodeDialog"
    @confirmNew="handleNewNode"
    @confirmEdit="handleEditNode"
  />
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import useApi from '@/core/apiStore'
import AddNodeDialog from './AddNodeDialog.vue'
import EditButton from '@/components/EditButton.vue'
import DeleteButton from '@/components/DeleteButton.vue'
import AddButton from '@/components/AddButton.vue'
import NodeModel from '@/models/NodeModel'
import { map } from 'lodash'
import { getIconUrl } from '@/components/topoIcons'
import { showConfirm, showAlert, showSuccessSaveMessage } from '@/utils'

const apiStore = useApi()

const addNodeDialog = ref(null)

onMounted(() => {
  apiStore.getNodes()
})
const handleAdd = () => {
  addNodeDialog.value.show()
}

const handleEdit = row => {
  addNodeDialog.value.show(row)
}

const tableSource = computed(() => {
  return map(apiStore.apiStates.getNodes.data, row => new NodeModel(row))
})

const handleNewNode = async newNode => {
  const isDuplicate = apiStore.apiStates.getNodes.data.some(
    item => item.ip === newNode.ip
  )

  if (isDuplicate) {
    showAlert(`IP地址 ${newNode.ip} 已存在，请勿重复添加`)
    return
  }
  apiStore.apiStates.getNodes.data.push(newNode)
  await saveNodes()
}

const handleEditNode = async (updatedNode: NodeModel) => {
  const index = apiStore.apiStates.getNodes.data.findIndex(
    item => item.ip === updatedNode.ip
  )
  if (index !== -1) {
    // 直接更新源数据而不是computed属性的结果
    Object.assign(apiStore.apiStates.getNodes.data[index], updatedNode)
  }

  await saveNodes()
}

const handleDelete = async (row: any) => {
  const index = apiStore.apiStates.getNodes.data.findIndex(
    item => item.ip === row.ip && item.name === row.name
  )
  if (index !== -1) {
    await showConfirm(`确认删除"${row.name}"吗`, async () => {
      apiStore.apiStates.getNodes.data.splice(index, 1)
      await saveNodes()
    })
  }
}

const saveNodes = async () => {
  await apiStore.setNodes({ items: apiStore.apiStates.getNodes.data })
  showSuccessSaveMessage()
}
</script>

<style scoped>
.table-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
}
</style>
